package cn.csxw.openchina.app;

import android.app.Application;

import com.zhy.autolayout.config.AutoLayoutConifg;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.csxw.openchina.constant.Constant;
import cn.csxw.openchina.interfaces.IOSChinaServer;
import cn.csxw.openchina.utils.Global;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

/**
 * App类
 */

public class ChinaApp extends Application {

//    public IOSChinaServer mOsChinaServer;
    @Override
    public void onCreate() {
        super.onCreate();
        File cacheDir = new File(getExternalCacheDir(), "responses");
        OkHttpClient client = new OkHttpClient.Builder()   //  添加请求超时时间
                .connectTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .cache(new Cache(cacheDir, 10 * 1024 * 1024))
                .addInterceptor(mInterceptor)
                .build();

        //初始化工具类
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .client(client)
                .build();
        IOSChinaServer  osChinaServer = retrofit.create(IOSChinaServer.class);
        Global.init(this,osChinaServer);
        AutoLayoutConifg.getInstance().useDeviceSize();
    }

    /** 缓存拦截器 */
    Interceptor mInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!Global.isNetworkReachable(getApplicationContext())) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            Response response = chain.proceed(request);
            if (Global.isNetworkReachable(getApplicationContext())) {
                int maxAge = 1000; // read from cache for 1 minute
                response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
                System.out.println("aaaaa");
            } else {
                int maxStale = 1000; // tolerate 4-weeks stale
                response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
                System.out.println("bbbb");
            }
            return response;
        }
    };

}
